package com.guigu.financial.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.guigu.financial.mapper.DictMapper;
import com.guigu.financial.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    //每6条存储一次 最大可存储3000,
    private static final int BATCH_COUNT = 6;

    private List<ExcelDictDTO> list = new ArrayList<>();

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条数据: {}",data);
        list.add(data);
        if (list.size() >= BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据已完成解析!");
    }

    public void saveData(){
        log.info("{} 条数据解析中",list.size());
        //批量插入
        dictMapper.insertBatch(list);
        log.info("{} 条数据解析完成!",list.size());
    }
}
